package com.ll.gulimall.order.web;

import com.ll.gulimall.order.entity.OrderReturnApplyEntity;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.util.UUID;

@RestController
public class SendMessageController {

    @Autowired
    RabbitTemplate rabbitTemplate;

    @GetMapping("/send")
    public String sendMessage(@RequestParam(value = "num", defaultValue = "10") Integer num) {
        for (int i = 0; i < num; i++) {
            OrderReturnApplyEntity en = new OrderReturnApplyEntity();
            en.setId(1L);
            en.setMemberUsername("哈哈哈" + i);
            rabbitTemplate.convertAndSend("hello-java-exchange", "hello1.java", en, new CorrelationData(UUID.randomUUID().toString()));
        }

        return "ok";
    }


    @RabbitListener(queues = {"hello-java-queue"})
    /**
     * 监听消息可以写以下类型
     * Message 消息头+消息体
     * result 消息数据 你发送时什么类型接受就什么类型
     * channel 接受消息的通道
     */
    public void getMessage(Message message, OrderReturnApplyEntity result, Channel channel) throws IOException {
       //通道的自增Id 用于手工确认
        long deliveryTag = message.getMessageProperties().getDeliveryTag();
        if(deliveryTag/2==0){
            //手工确认 param1：通道Id param2:是否批量确认
            //没有确认的会重新进入队列
            channel.basicAck(deliveryTag,true);
            //手工拒绝 param1:通道id param2:批量拒绝 param3:是否重新进入队列
            channel.basicNack(deliveryTag,false,true);
            //channel.basicReject();→同上 （非批量）
            System.out.println("手工确认了"+deliveryTag);
        }

        System.out.println("接受到消息了" + result);

    }

}
